package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.service.OrdersService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class OrderTask {

    @Autowired
    OrdersMapper ordersMapper;

    // 每分钟执行一次
    @Scheduled(cron = "0 * * * * *")
    public void processTimeoutOrder() {
        // 当前时间减去15分钟
        LocalDateTime now = LocalDateTime.now().minusMinutes(15);
        // 找到状态为带付款和订单时间已经超过15分钟的
        // 如果订单时间<当前时间-15分钟  说明订单已经超过15分钟了
        //在sql中获取当前时间-15分钟NOW() - INTERVAL 15 MINUTE;
        List<Orders> ordersList = ordersMapper.findAll(Orders.PENDING_PAYMENT, now);

        if (ordersList != null && ordersList.size() != 0) {
            ordersList.forEach(orders -> {
                // 修改状态和取消信息
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("支付超时，自动取消");
                orders.setCancelTime(LocalDateTime.now());
                ordersMapper.updateById(orders);
            });
        }
    }
}
